// pages/customer/submit.js
import Validate from "../../utils/validate";
import Toast from '@vant/weapp/toast/toast';

const app = getApp();
const network = require("../../utils/network.js");
const util = require("../../utils/util.js");

Page({

    /**
     * 页面的初始数据
     */
    data: {
        customer: {
            id: null,
            name: null,// 名称
            industry_id: null,// 行业id
            address: null,// 地址
            funnels: [],// 销售漏斗
            selection_reasons: [],// 选择原因
            budget: null,// 预算
            person_in_charge_id: null,// 负责人id
            group: null,// 所属集团id
            company_launch_background: null,// 客户投放背景
            company_programme: null,//客户方案
            industry_name: null,// 显示文本
            group_name: null,// 显示文本
            person_in_charge_name: null,// 显示文本
        },
        industryPopShow: false,
        groupPopShow: false,
        userSelectShow: false,
        industry_arr: [],// 行业待选项
        salesFunnelArr: [],// 销售漏斗待选项
        groupArr: [],//所属集团待选项
        userArr: [],// 客户负责人待选项
        validate: {},
        wf_data_id: -1,
        user_id: wx.getStorageSync('user_id'),
        customerTmp: {},
        dialogShow: false
    },
    // 验证函数
    initValidate() {
        const rules = {
            name: {
                required: true
            },
            industry_id: {
                required: true
            },
            address: {
                required: true,
            },
            person_in_charge_id: {
                required: true
            },
            group: {
                required: true
            }
        }
        const messages = {
            name: {
                required: '请输入项目名称'
            },
            industry_id: {
                required: '请选择行业'
            },
            address: {
                required: '请输入客户地址',
            },
            person_in_charge_id: {
                required: '请选择客户负责人'
            },
            group: {
                required: '请选择集团'
            },
        }
        this.data.validate = new Validate(rules, messages)
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        util.showLoading('加载中')
        if (options.wf_data_id) {
            this.setData({
                wf_data_id: options.wf_data_id,
            })
        }
        const that = this
        this.initValidate()
        Promise.all([
            this.getDictList('khxg-hy', 'industry_arr', '行业数据初始化失败'),
            this.getDictList('khxg-xzyy', 'selectReasonArr', '选择原因数据初始化失败'),
            this.getDictList('khxg-xsld', 'salesFunnelArr', '销售漏斗数据初始化失败'),
            this.getDictList('khxg-ssjt', 'groupArr', '所属集团数据初始化失败'),
            this.getUserArr()
        ]).then(() => {
            network.reqPromise('GET', {
                uri: app.api.editDetail,
                params: {id: options.id},
            }).then(res => {
                res.data.funnels = res.data.funnels.map(i => {
                    return i.toString()
                })
                res.data.selection_reasons = res.data.selection_reasons.map(i => {
                    return i.toString()
                })
                that.setData({
                    customer: res.data
                })
            }).catch(() => {

            })
            util.hideLoading()
        }).catch(() => {
            util.hideLoading()
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.selectComponent('.flow-btn-group').callbackBeforeConfirm = this.validForm;
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    //初始化字典数据
    getDictList(code, data, failMsg) {
        const that = this
        return new Promise((resolve, reject) => {
            network.reqPromise('GET', {
                uri: app.api.getDictData,
                params: {code: code}
            }).then(res => {
                that.setData({
                    [data]: res.data
                })
                resolve()
            }).catch(() => {
                Toast.fail({
                    message: failMsg,
                    context: that,
                    selector: '#custom-selector'
                });
                reject()
            })
        })
    },
    // 初始化人员信息
    getUserArr() {
        const that = this
        return new Promise((resolve, reject) => {
            network.reqPromise('GET', {
                uri: app.api.allUserList
            }).then(res => {
                that.setData({
                    userArr: res.data
                })
                resolve()
            }).catch(() => {
                Toast.fail({
                    message: '初始化用户数据失败',
                    context: that,
                    selector: '#custom-selector'
                });
                reject()
            })
        })
    },
    // 输入框输change
    onInputChange(e) {
        const key = e.target.dataset.key;
        this.setData({
            [key]: e.detail
        })
        this.watch()
    },
    // 显示弹出层
    showPopup(e) {
        if (this.data.customer.flow_status === 3 || this.data.customer.flow_status === 4) {
            return
        }
        let key = e.target.dataset.show;
        this.setData({
            [key]: true
        })
    },
    // 确认选择行业
    onConfirmIndustry(e) {
        this.setData({
            'customer.industry_id': e.detail.value.id,
            'customer.industry_name': e.detail.value.name,
            industryPopShow: false
        });
    },
    // 确认选择客户负责人
    onConfirmUser(e) {
        this.setData({
            'customer.person_in_charge_id': e.detail.value.id,
            'customer.person_in_charge_name': e.detail.value.name,
            userSelectShow: false
        });
    },
    // 取消选择
    onCancelPop(e) {
        let key = e.target.dataset.show;
        this.setData({
            [key]: false,
        });
    },
    // 多选框选择事件
    onCheckBoxChange(e) {
        const key = e.target.dataset.key;
        this.setData({
            [key]: e.detail,
        });
    },
    // 确认选择集团
    onConfirmGroup(e) {
        this.setData({
            'customer.group': e.detail.value.id,
            'customer.group_name': e.detail.value.name,
            groupPopShow: false
        });
    },
    validForm() {
        if (!this.data.validate.checkForm(this.data.customer)) {
            this.setData({
                active: 0
            })
            Toast.fail({
                message: this.data.validate.errorList[0].msg,
                context: this,
                selector: '#custom-selector'
            })
            return false
        } else {
            // 检查漏斗信息
            if (this.data.customer.funnels.length) {
                return true
            } else {
                Toast.fail({
                    message: '请选择漏斗信息',
                    context: this,
                    selector: '#custom-selector'
                })
                return false
            }
        }
    },
    save() {
        const that = this
        util.showLoading('保存中')
        network.reqPromise('POST', {
            uri: app.api.editSave,
            params: that.data.customer,
        }).then(res => {
            util.hideLoading()
            Toast.success({
                message: '操作成功',
                context: that,
                selector: '#custom-selector'
            })
            setTimeout(() => {
                this.back()
            }, 800)
        }).catch(() => {
            Toast.fail({
                message: '操作失败',
                context: that,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    submit() {
        const that = this
        util.showLoading('保存中')
        network.reqPromise('POST', {
            uri: app.api.editSubmit,
            params: that.data.customer,
        }).then(res => {
            util.hideLoading()
            Toast.success({
                message: '操作成功',
                context: that,
                selector: '#custom-selector'
            })
            setTimeout(() => {
                this.back()
            }, 800)
        }).catch(() => {
            Toast.fail({
                message: '操作失败',
                context: that,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    pass(opinion) {
        const that = this
        util.showLoading('提交中')
        network.reqPromise('POST', {
            uri: app.api.editPass,
            params: {
                id: that.data.customer.id,
                wf_check_opinion: opinion.detail,
            },
        }).then(res => {
            util.hideLoading()
            Toast.success({
                message: '操作成功',
                context: that,
                selector: '#custom-selector'
            })
            setTimeout(() => {
                this.back()
            }, 800)
        }).catch(() => {
            Toast.fail({
                message: '操作失败',
                context: that,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    returnBack(opinion) {
        const that = this
        util.showLoading('提交中')
        network.reqPromise('POST', {
            uri: app.api.editReturnBack,
            params: {
                id: that.data.customer.id,
                wf_check_opinion: opinion.detail,
            },
        }).then(res => {
            util.hideLoading()
            Toast.success({
                message: '操作成功',
                context: that,
                selector: '#custom-selector'
            })
            setTimeout(() => {
                this.back()
            }, 800)
        }).catch(() => {
            Toast.fail({
                message: '操作失败',
                context: that,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    del() {
        const that = this
        util.showLoading('提交中')
        network.reqPromise('POST', {
            uri: app.api.editDel,
            params: {
                id: that.data.customer.id
            },
        }).then(res => {
            util.hideLoading()
            Toast.success({
                message: '操作成功',
                context: that,
                selector: '#custom-selector'
            })
            setTimeout(() => {
                this.back()
            }, 800)
        }).catch(() => {
            Toast.fail({
                message: '操作失败',
                context: that,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    actDel() {
        const that = this
        util.showLoading('提交中')
        network.reqPromise('POST', {
            uri: app.api.editActualDelete,
            params: {
                id: that.data.customer.id
            },
        }).then(res => {
            util.hideLoading()
            Toast.success({
                message: '操作成功',
                context: that,
                selector: '#custom-selector'
            })
            setTimeout(() => {
                this.back()
            }, 800)
        }).catch(() => {
            Toast.fail({
                message: '操作失败',
                context: that,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    },
    preventTouchMove() {

    },
    onDialogClose() {
        this.setData({
            dialogShow: false,
            customerTmp: {}
        })
    },
    back() {
        wx.navigateBack({
                delta: 1
            }
        )
    },
    showDialog() {
        this.setData({
            dialogShow: true,
        })
        util.showLoading('加载中')
        network.reqPromise('GET', {
            uri: app.api.customerInfoDetail,
            params: {
                id: this.data.customer.customer_id
            },
        }).then(res => {
            res.data.funnels = res.data.funnels.map(i => {
                return i.toString()
            })
            res.data.selection_reasons = res.data.selection_reasons.map(i => {
                return i.toString()
            })
            this.setData({
                customerTmp: res.data
            })
            util.hideLoading()
        }).catch(() => {
            Toast.fail({
                message: '操作失败',
                context: this,
                selector: '#custom-selector'
            })
            util.hideLoading()
        })
    }
})
